<?php
class Character{
	/**
	 * Filter The HTML Character
	 */
	public static function HTMLToDbEncode($str){
		$str = trim($str);
		return htmlspecialchars($str,ENT_QUOTES);
	}

	public static function HTMLToDbDecode($str){
		return htmlspecialchars_decode($str,ENT_QUOTES);
	}

	/** * 获取指定长度的字符{{{
	 *
	 * @param unknown_type $stringValue
	 * @param unknown_type $length
	 * @param unknown_type $postfix
	 * @param unknown_type $encoding
	 * @return unknown
	 */
	public static function subStr($stringValue,$length=0,$postfix='...',$encoding='UTF-8'){
		if($stringValue==null){
			return '';
		}

		$stringValue=preg_replace("/&(amp;)+/","&",$stringValue);//将过度编码的html还原成只编码过一次的
		$stringValue=htmlspecialchars_decode($stringValue);
		$stringValue=preg_replace("/<[b|B][r|R] {0,1}\/{0,1}>/", "\r\n", $stringValue);//将用户输入的<br />符转为回车符
		$stringValue=preg_replace("/(\r?\n){4,}/","\r\n\r\n\r\n",$stringValue);//for BETA-2684：连续换行（回车）不超过3行，超过的自动保留3行
		$realLen = mb_strwidth($stringValue,$encoding);
		if(!is_numeric($length) or $length*2 >= $realLen){
			return htmlspecialchars($stringValue, ENT_QUOTES,$encoding);
		}

        $stringValue = mb_strimwidth($stringValue,0,$length*2,$postfix,'UTF-8');
		return htmlspecialchars($stringValue, ENT_QUOTES,$encoding);
	}
	/*}}}*/
}
